package com.campus.dao.impl;

import com.campus.dao.StudentInClassDao;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

@Repository
@Slf4j
public class StudentInClassDaoImpl implements StudentInClassDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public String addStudentsToClass(int classId, List<Integer> studentIds) {

        if (!isValidClassId(classId)) {
            return "未找到班级";
        }

        for (Integer studentId : studentIds) {
            if (!isValidStudentId(studentId)) {
                return "未找到学生";
            }
        }

        String sql = "INSERT INTO t_teaching_student_in_class (class_id, student_id) VALUES (?, ?)";
        int[] results = jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
            @Override
            public void setValues(PreparedStatement ps, int i) throws SQLException {
                ps.setInt(1, classId);
                ps.setInt(2, studentIds.get(i));
            }

            @Override
            public int getBatchSize() {
                return studentIds.size();
            }
        });

        return results.length > 0 ? "学生添加成功" : "学生添加失败";
    }

    // 检查班级 ID 是否有效
    private boolean isValidClassId(int classId) {
        String sql = "SELECT 1 FROM t_manager_class WHERE id = ?";
        return jdbcTemplate.queryForObject(sql, Boolean.class, classId);
    }

    // 检查学生 ID 是否有效
    private boolean isValidStudentId(int studentId) {
        String sql = "SELECT 1 FROM t_manager_student WHERE id = ?";
        return jdbcTemplate.queryForObject(sql, Boolean.class, studentId);
    }

    @Override
    public List<Integer> getStudentsByClassId(int classId) {
        String sql = "SELECT student_id FROM t_teaching_student_in_class WHERE class_id = ?";
        return jdbcTemplate.queryForList(sql, Integer.class, classId);
    }

}
